<?php

namespace app\admin\controller\Utils;

use app\BaseController;
use think\Exception;
use think\exception\ValidateException;
use think\facade\Filesystem;
use ZIPARCHIVE;

class ZipGetFilePath extends BaseController
{
    public function test()
    {
        $file_path_name = $this->upload();

        $res = $this->unzip($file_path_name['file_path'], $file_path_name['file_name']);

        print_r($res);
    }

    /**
     * 接收文件上传
     * @return array
     */
    public function upload()
    {
        // 获取表单上传文件
        if (empty(request()->file('file'))) {
            $this->error("请上传文件！");
        }

        try {
            $file = request()->file();
        } catch (\Exception $e) {
            $this->error("文件上传失败");
        }

        try {
            // 验证文件大小，名称等是否正确
            validate(['file' => 'filesize:52428800|fileExt:zip'])
                ->check($file);
        } catch (ValidateException $e) {
            $this->error($e->getMessage());
        }

        $file_path = root_path('runtime') . 'storage/';
        $file_name = Filesystem::putFile(date('Ymd') . '/' . 'zip', $file['file']);


        return [
            'file_path' => $file_path,
            'file_name' => $file_name,
        ];
    }

    /**
     * 解压文件，开始遍历
     * @throws Exception
     * @throws \Exception
     */
    public function unzip($file_path, $file_name)
    {
        $zip = new ZipArchive;

        // 打开文件
        if (!$zip->open($file_path . $file_name)) {
            throw new Exception('读取文件失败');
        }

        // 解压文件
        $seed = random_bytes(32);
        if (!$zip->extractTo($file_path . date('Ymd') . '/' . $seed . '/')) {
            // 关闭
            $zip->close();
            return false;
        }


    }
}